<script setup>

import {
  defineModel,
  defineProps,
  getCurrentInstance,
  onMounted,
  nextTick,
  toRaw,
  ref,
  computed,
  onUpdated,
  reactive, watchEffect, watch, toRefs, toRef
} from "vue";
import Sortable from "sortablejs";
import {clearAndPushAll} from "@/utils/ArrayUtil";
import HTMLContentable from "@/components/HTMLContentable.vue";
import TinyMCECustomed from "@/components/TinyMCECustomed.vue";
import {orderBy} from "lodash-unified";
import {Edit} from "@element-plus/icons-vue";


const model = defineModel();
let props = defineProps(["theParentTable", "theFormPos"]);

let theTableIn = ref();

let expandedRowKeys = reactive([]);

let sortChangeObjRef = ref({});

const rowMoreInfos = reactive(new Map());
// new Map().has("sss")
let theRowSortable;
//
// watch(props.theFormPos,newVal=>{
//
// })

function onSortChanged(sortingColumnInfoProxy) {
    sortChangeObjRef.value = sortingColumnInfoProxy;
}

function onExpandeChange(currOperRowModel,expandedRows){
    // console.log("onExpandeChange",currOperRowModel,expandedRows);
    clearAndPushAll(expandedRowKeys,[...expandedRows.map(ele=>ele.subId)]);
    if(expandedRows.indexOf(currOperRowModel)===-1&&rowMoreInfos.get(currOperRowModel.subId)!==undefined){
        //当前行收起
        rowMoreInfos.get(currOperRowModel.subId).editingExamples = false;
    }else{
        //当前行展开

    }
    // console.log("currOperRowModel",currOperRowModel,expandedRows,expandedRows.indexOf(currOperRowModel));
    // if(expandedRows.length>0){
    //     theRowSortable.options.disabled = true;
    // }else{
    //     theRowSortable.options.disabled = false;
    // }
}


watchEffect(()=>{

    console.log("watched effect 2");

    let aa = expandedRowKeys[0];
    sortChangeObjRef.value;

    if(!theRowSortable){
        return;
    }

    if(sortChangeObjRef.value.order){
        theRowSortable.options.disabled = true;
    }else if(expandedRowKeys.length>0){
        theRowSortable.options.disabled = true;
    }else{
        theRowSortable.options.disabled = false;
    }

})

function rowClassNameIt(theRowInfo) {
    // console.log("rowClassNaming it:",theRowInfo);
    // if(theTableIn.value){
    //     // console.log("theTableIn");
    // }
    let theRowDom = theTableIn?.value?.$el?.querySelectorAll(".el-table__row")[theRowInfo.rowIndex];
    if (theRowDom) {
        theRowDom?.setAttribute("data-id", theRowInfo?.row?.subId);
        // if (theRowInfo.rowIndex === props.theFormPos?.poses?.length - 1) {
        //
        //     let querySelectedAll = theRowDom?.querySelectorAll('td.el-table__cell .cell');
        //     if(querySelectedAll&&querySelectedAll?.length>0&&!(querySelectedAll[3]?.querySelectorAll('[sorter]').length>0)){
        //         let sorterDiv = document.createElement("div");
        //         sorterDiv.setAttribute("sorter","");
        //         sorterDiv.innerHTML = `<i class="fas fa-arrows-up-down"></i>`;
        //         querySelectedAll[3].appendChild(sorterDiv);
        //         // console.log("theRowDom:,", querySelectedAll);
        //     }
        //
        // }
    }

    // console.log("theTable:",theTable?.value);
    return "";
}

let sorting = ref('');

let cptViewingModeSortedData = computed(()=>{

})


const rowDrop = () => {
    // console.log("rowdrop");
    const instance = getCurrentInstance();
    // const tbody = document.querySelector('.compactPopover .el-table__body-wrapper tbody');
    // console.log("subtable instance:",instance);
    const tbody = instance?.ctx?.$el?.parentNode.querySelector(".el-table__body-wrapper tbody");
    // console.log("the sub table model:", model);
    theRowSortable = Sortable.create(tbody, {
        // draggable: ".pwSubTable .el-table__row",
        handle: ".pwSubTable .handle",
        dataIdAttr: "data-id",
        group:props.theFormPos.form,
        animation: 100,
        onEnd(evt) {

            let arr = model.value ? model.value : props.theFormPos.poses; // 获取表数据
            arr.splice(evt.newIndex, 0, arr.splice(evt.oldIndex, 1)[0]); // 数据处理，获取最新的表格数据
            // console.log("the arr:",arr);
            let arrtemp = [...toRaw(arr)];
            // console.log("thePoses:",props.theFormPos?.poses);
            nextTick(function () {
                let rows  = theTableIn?.value?.$el?.querySelectorAll(".el-table__row");
                for (const row of rows) {
                    row?.setAttribute("data-id", row.__vnode.key);
                }
                // let showing  = [...tbody.querySelectorAll(".el-table__row")].map(ele=>ele.textContent).join("\n");

                let showing = theRowSortable.toArray().join("\n");
                // console.log("showing",showing);
                let dataTexts = arr.map(ele => ele.subId).join("\n");
                // console.log("dataTexts",dataTexts);
                if (showing !== dataTexts) {
                  //这个sortable会有bug，当倒数第二行和倒数第一行互换后，任意非倒数第二行的行和倒数第一行互换时，界面都会出错，所以再sort一次。
                    theRowSortable.sort(arr.map(ele => ele.subId), false);
                    // console.log("errored order",arrtemp);
                }
            })

            // let theData = model.value ? model.value : props.theFormPos.poses;
            // console.log("row dragged");
            // const currRow = theData.splice(evt.oldIndex, 1)[0];
            // theData.splice(evt.newIndex, 0, currRow);
            // console.log(gridData);
        }
    });


    // theRowSortable.options.disabled = true;
}

function customHeaderCellClass({ column, $index }) {
  console.log("customHeaderCellClass,",column,$index)
  if (column.property === 'name') {
    return 'custom-header-class';
  }
  return '';
}

onUpdated(()=>{
    console.log("onUpdated:",theTableIn?.value?.$el?.querySelectorAll(".el-table__row"));
})


onMounted(() => {
    // console.log("DraggableElTable.vue mounted");
    // const instance = getCurrentInstance();
    // console.log("the instance,",instance)
    console.log("parent table:,", props.theParentTable, getCurrentInstance())
    rowDrop();
})
</script>

<template>
  <!--  :data="model?model:thePoses"-->
  <!--  {{thePoses}}-->
  <!--    {{expandedRowKeys}}-->
  <!--  :expand-row-keys="expandedRowKeys"-->
  <!--  expandedRowKeys:{{expandedRowKeys}}-->
  <!--  sortChangeObjRef:{{sortChangeObjRef}}-->
  <!--  default-expand-all-->
  <el-table
      ref="theTableIn"
      :data="model?model:theFormPos.poses"
      :width="300"
      :border="true"
      :row-class-name="rowClassNameIt"
      @sortChange="onSortChanged"
      @expandChange="onExpandeChange"

      row-key="subId">
    <!--        <el-table-column width="35" :label="theFormPos.form" :align="`left`" :resizable="false" :header-cell-class-name="customHeaderCellClass"></el-table-column>-->
    <el-table-column width="45"  :class-name="`aa`">


    </el-table-column>
    <el-table-column width="80" type="expand" :label="theFormPos.form" :align="`left`" :resizable="false">
      <template #header>
        {{ theFormPos.form }}<i class="fas fa-up-down handle-forms"></i>
      </template>
      <template #default="theData">
        <div v-if="rowMoreInfos.get(theData.row.subId)?.editingExamples===undefined||rowMoreInfos.get(theData.row.subId)?.editingExamples===false" style="padding:2px 20px">
          <HTMLContentable v-if="theData.row.examples"
                           :contentHtmlStr="theData.row.examples"></HTMLContentable>
        </div>
        <TinyMCECustomed
            v-if="rowMoreInfos.get(theData.row.subId)?.editingExamples===true"
            v-model="theData.row.examples"
            :showContenRawTag="false"
            :pwidth="560"
            :pheight="400"
            @remarkEditDone="rowMoreInfos.get(theData.row.subId).editingExamples=false"></TinyMCECustomed>
      </template>
    </el-table-column>
    <el-table-column width="150" property="text" label="">
      <!--            <template #header>-->
      <!--                <el-button @click="theFormPos.poses.push({subId: ``, text: 'restraint1', relevancyD:50,moreOfSense:'',moreOfCoreConcepts:'',tldRank:5479,tldFreq:4571,tldFormPerc:100,tldSensePerc:100,remarks: [],examples:``})">+</el-button>-->
      <!--            </template>-->
      <template #default="theData">
        <i class="fas fa-up-down handle"></i><span style="margin-left: 5px;color: #b2492a"><b>{{ theData.row.text }}</b></span>
      </template>
    </el-table-column>
    <el-table-column width="100" property="relevancyD" :label="`相关度`" sortable>
      <template #default="theData">
        {{theData.row.relevancyD}}
        <!--                {{theData.row}}{{theData.$index}}{{theData.column}}-->

        <!--                <div v-if="theData.$index===theFormPos.poses.length-1" style="float: right"><i class="fas fa-arrows-up-down"></i></div>-->
        <div v-if="theData.$index===theFormPos.poses.length-1" style="float: right">
          <!--                    <i class="fa-solid fa-arrow-down-9-1"></i>-->
          <!--                    <i class="fa-solid fa-arrow-down-1-9"></i>-->
          <i class="fa-solid fa-arrow-down-wide-short" @click="clearAndPushAll(theFormPos.poses,orderBy(theFormPos.poses,['relevancyD'],['desc']));console.log(`down wide`,theFormPos.poses)"></i>
<!--          <i class="fa-solid fa-arrow-down-short-wide" @click="clearAndPushAll(theFormPos.poses,orderBy(theFormPos.poses,['relevancyD'],['asc']));console.log(`down wide`,theFormPos.poses)"></i>-->
        </div>
      </template>
    </el-table-column>
    <el-table-column width="99"></el-table-column>
    <el-table-column :resizable="false">
      <!--            v-if="expandedRowKeys.indexOf(theData.row.subId)>-1"-->
      <template #header>
        <button class="my-button">+</button>
      </template>
      <template #default="theData">
<!--        <button class="my-button">+</button>-->
        <button class="my-button"
                style="padding:5px;margin-right: 2px;"
                v-if="rowMoreInfos.get(theData.row.subId)===undefined||rowMoreInfos.get(theData.row.subId).editingExamples===false"
                @click="()=>{
                    theTableIn.toggleRowExpansion(theData.row,true);
                    console.log(`theData`,theData);
                    console.log(`rowMoreInfos`,rowMoreInfos);
                    if(rowMoreInfos.has(theData.row.subId)){
                        rowMoreInfos.get(theData.row.subId).editingExamples = !rowMoreInfos.get(theData.row.subId).editingExamples;
                        console.log(`subId`,theData.row.subId,rowMoreInfos.get(theData.row.subId).editingExamples);
                    }else{
                        rowMoreInfos.set(theData.row.subId,{editingExamples:true});
                        console.log(`subId`,theData.row.subId,rowMoreInfos.get(theData.row.subId).editingExamples);
                    }
                }"><el-icon><Edit /></el-icon></button>
        <button class="my-button" style="width: 26px">-</button>
      </template>
    </el-table-column>
  </el-table>
  <!--    <div>-->
  <!--        <i class="fas fa-camera" @click="console.log(`show the data1:`,theFormPos.poses)"></i> &lt;!&ndash; 举例一个相机图标 &ndash;&gt;-->
  <!--        <i class="fas fa-arrow-up-wide-short"></i> &lt;!&ndash; 举例一个相机图标 &ndash;&gt;-->
  <!--        <i class="fas fa-arrow-up-short-wide"></i> &lt;!&ndash; 举例一个相机图标 &ndash;&gt;-->
  <!--        <i class="fas fa-arrow-down-short-wide"></i> &lt;!&ndash; 举例一个相机图标 &ndash;&gt;-->
  <!--        <i class="fas fa-arrow-down-wide-short"></i> &lt;!&ndash; 举例一个相机图标 &ndash;&gt;-->
  <!--        <i class="fas fa-arrows-up-down"></i> &lt;!&ndash; 举例一个相机图标 &ndash;&gt;-->
  <!--    </div>-->

  <!--  {{model}}-->
</template>

<style scoped>
.fas {
    font-size: 12px;
}

.fas:not(.handle):hover {
    color: #1e55dc;
}

.fa-solid:hover{
    color: #1e55dc;
}

.handle {
    width: 20px;
    cursor: grab;
}

.handle-forms {
    width: 20px;
    cursor: grab;
}

:global(.pwSubTable .el-table__header-wrapper) {
    /*display: none;*/
    border:none;

    :global(th.el-table__cell.is-leaf:first-child div.cell){
        text-align: left;
    }

    :global(.cell) {
        line-height: 16px;
        /*text-align: right;*/
        text-align: left;
    }

    :global(span.caret-wrapper){
        /*display: none;*/
    }

    :global(.el-table .el-table__cell) {

    }
}

:global(.pwSubTable .el-table th.el-table__cell.is-leaf:first-child){
    /*border: var(--el-table-border);*/
    /*border: 1px solid red;*/
    border-left: none;
    border-right: none;
    border-top: none;
}
:global(.pwSubTable .el-table th.el-table__cell.is-leaf:not(:first-child)){
    /*border: var(--el-table-border);*/
    /*border: 1px solid red;*/
    /*border-left: 1px dashed;*/
    border-right: 1px dashed #ebeef5;
    border-top: none;
}
</style>